package main

import (
	"./config"
	"context"
	"database/sql"
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

var db *sql.DB

func main() {
	gin.DisableConsoleColor()
	// get config path args
	//confpath := flag.String("confpath", "./.env", "config file path")
	//fmt.Println(*confpath)
	//config.LoadConfig(*confpath)
	// Logging to a file.
	logconf, _ := config.GetLogConf()
	f, _ := os.Create(logconf.Path)
	gin.DefaultWriter = io.MultiWriter(f)

	// init mysql
	dbconf, _ := config.GetDBConf("mysql")
	var err error
	constr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true",
		dbconf.User,
		dbconf.Password,
		dbconf.Host,
		dbconf.Port,
		dbconf.DB)
	fmt.Println(constr)
	db, err = sql.Open("mysql", constr)

	if err != nil {
		log.Fatalln(err)
	}
	defer db.Close()
	db.SetMaxIdleConns(20)
	db.SetMaxOpenConns(20)
	if err := db.Ping(); err != nil {
		log.Fatalln(err)
	}

	// Set gin router
	router := gin.Default()
	router.POST("/login", Login)
	router.POST("/register", Register)
	pay := router.Group("/pay")
	{
		pay.POST("/order", Order)
		pay.POST("/alipaynotify", AlipayNotify)
		pay.POST("/wxpaynotify", WxpayNotify)
	}

	srv := &http.Server{
		Addr:    ":8080",
		Handler: router,
	}

	// Initializing the server in a goroutine so that
	// it won't block the graceful shutdown handling below
	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
		// http.ListenAndServeTLS(addr, certFile, keyFile, engine)
		// Listen and Server in https://127.0.0.1:8080
		//router.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")
	}()

	// Wait for interrupt signal to gracefully shutdown the server with
	// a timeout of 5 seconds.
	quit := make(chan os.Signal)
	// kill (no param) default send syscall.SIGTERM
	// kill -2 is syscall.SIGINT
	// kill -9 is syscall.SIGKILL but can't be catch, so don't need add it
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shutting down server...")

	// The context is used to inform the server it has 5 seconds to finish
	// the request it is currently handling
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server forced to shutdown:", err)
	}

	log.Println("Server exiting")
}

func notFound(c *gin.Context) {
	c.String(http.StatusNotFound, "404 ,page not exists!")
}
